<?
require_once('DataMediatorModel.php');
require_once('DataMediatorError.php');

require_once('ri/converter/Converter.php');
require_once('ri/validator/Validator.php');

class DataMediatorField {
	private $list,$name,$converter;
	private $validators= array();
	
	public function __construct(DataMediatorModel $list,$name,Converter $converter) {
		$this->list= $list;
		$this->name= $name;
		$this->converter= $converter;
	}
	public function getConverter() {
		return $this->converter;
	}
	public function addValidator(Validator $validator) {
		$this->validators[]= $validator;
		return $this;
	}
	public function getAsString() {
		// return converted value
		try {
			$value= $this->getAsDatatype();
			// prevent the converter to return the default value
			if (is_null($value)) return '';
			// return formatted string for value
			return $this->converter->getAsString($value);
		}
		catch (ConverterException $e) {
			// if value couldnt be converted return string straight from list
			return $this->list->get($this->name);
		}
	}
	public function getAsDatatype() {
		return $this->converter->getAsDatatype($this->list->get($this->name));
	}
	/**
	 * Determines if a value object is valid.
	 * Checks if the value can be converted and validates it.
	 *
	 * @return bool Valid or not.
	 */
	public function isValid() {
		try {
			$value= $this->getAsDatatype();
			foreach ($this->validators as $validator) {
				$validator->validate($value);
			}
			// return true if no error occured
			return true;
		}
		catch (Exception $e) {
			// return false on error
			return false;
		}
	}
	/**
	 * Returns a list of errors for this value.
	 * The result is an array either empty or it contains DataMediatorError objects.
	 *
	 * @return array List of errors.
	 */
	public function getErrors() {
		$errors= array();
		// converter
		try {
			$value= $this->getAsDatatype();
			// validators
			foreach ($this->validators as $validator) {
				try {
					$validator->validate($value);
				}
				catch (ValidatorException $e) {
					$errors[]= new DataMediatorError($e);
				}
			}
		}
		catch (ConverterException $e) {
			$errors[]= new DataMediatorError($e);
		}
		return $errors;
	}
}
